package com.dhapi.demo.web.filter;

import redis.clients.jedis.Jedis;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.io.Serializable;
import java.util.Enumeration;

public class InHttpSession implements HttpSession {


    private HttpSession session;
    private String sid;

    private Jedis jedis;

    public InHttpSession(String sid,HttpSession session) {
        this.sid = sid;
        this.session = session;
        jedis = new Jedis("127.0.0.1");
    }

    @Override
    public long getCreationTime() {
        return session.getCreationTime();
    }

    @Override
    public String getId() {
        return sid;
    }

    @Override
    public long getLastAccessedTime() {
        return session.getLastAccessedTime();
    }

    @Override
    public ServletContext getServletContext() {
        return session.getServletContext();
    }

    @Override
    public void setMaxInactiveInterval(int interval) {
         session.setMaxInactiveInterval(interval);
    }

    @Override
    public int getMaxInactiveInterval() {
        return session.getMaxInactiveInterval();
    }

    @Override
    public HttpSessionContext getSessionContext() {
        return session.getSessionContext();
    }

    @Override
    public Object getAttribute(String name) {
        byte[] arr = jedis.get(("s." + sid + "." + name).getBytes());
        return SerializeUtil.jdeserialize(arr);
    }


    @Override
    public Object getValue(String name) {
        return getAttribute(name);
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return new Enumeration<String>() {
            @Override
            public boolean hasMoreElements() {
                return false;
            }

            @Override
            public String nextElement() {
                return null;
            }
        };
    }

    @Override
    public String[] getValueNames() {
        return new String[0];
    }

    @Override
    public void setAttribute(String name, Object value) {
        byte[] arr = SerializeUtil.jserialize(value);
        jedis.set(("s."+sid+"."+name).getBytes(), arr);

    }

    @Override
    public void putValue(String name, Object value) {
        setAttribute(name,value);
    }

    @Override
    public void removeAttribute(String name) {
        System.out.println("待实现");
    }

    @Override
    public void removeValue(String name) {
        removeValue(name);
    }

    @Override
    public void invalidate() {
        System.out.println("待实现");
    }

    @Override
    public boolean isNew() {
        return session.isNew();
    }
}
